package org.clockworkmages.games.anno1186.gui;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;

import org.clockworkmages.games.anno1186.GameBeansContext;
import org.clockworkmages.games.anno1186.GameState;
import org.clockworkmages.games.anno1186.GameStateService;
import org.clockworkmages.games.anno1186.dao.FileUtil;
import org.clockworkmages.games.anno1186.model.map.tactical.GameArea;
import org.clockworkmages.games.anno1186.model.map.tactical.Tile;
import org.clockworkmages.games.anno1186.model.map.tactical.TileObject;

public class LocalMapPanel
		extends JPanel {

	@Override
	public void paintComponent(final Graphics g) {

		GameStateService gameStateService = GameBeansContext
				.getBean(GameStateService.class);
		if (gameStateService == null) {
			return;
		}
		GameState gameState = gameStateService.getGameState();
		GameArea gameArea = gameState.getGameArea();
		if (gameArea == null) {
			return;
		}

		super.paintComponent(g);

		int myX = gameState.getLocalMapX();
		int myY = gameState.getLocalMapY();

		for (int row = 0; row < 7; row++) {
			int startAt = 0;
			// = Math.abs(row - 3) - 1;
			// if (startAt == -1) {
			// startAt = 0;
			// }
			for (int column = 6; column >= 0; column--) {
				if (column >= startAt && column <= 6 - startAt) {

					int tileY = myY - row + 3;
					int tileX = myX + column - 3;
					if (tileX >= 0 && tileX < gameArea.getTiles().length
							&& tileY >= 0
							&& tileY < gameArea.getTiles()[tileX].length) {
						Tile tile = gameArea.getTiles()[tileX][tileY];
						for (TileObject tileObject : tile.getTileObjects()) {
							String image = tileObject.getImage();
							if (image != null) {
								// TODO all Images should be cached
								Image tileImage = FileUtil
										.getResourceAsImage("images/map/"
												+ image + ".png");

								// final BufferedImage tileImage = ImageIO
								// .read(new URL(
								// "classpath://images/map/"
								// + image + ".png"));

								g.drawImage(tileImage, (column) * 40
										+ (row - 2) * 18
										//
										- tileImage.getWidth(null) + 40, (row)
										* 20
										//
										- tileImage.getHeight(null) + 28, null);
							}

						}
					}
					if (row == 3 && column == 3) {
						Image tileImage = FileUtil
								.getResourceAsImage("images/map/" + "hummie"
										+ ".png");
						g.drawImage(tileImage, (column) * 40 + (row - 2) * 18
						//
								- tileImage.getWidth(null) + 40, (row) * 20
						//
								- tileImage.getHeight(null) + 28, null);
					}
				}
			}

		}
	};

}
